<?php

/**
 * 用户体系集成操作
 */
namespace Api\Controller;
use Api\Controller\HxController;
class AppUserController extends HxController {
	private $ACTION1 = '1';// 好友删除
	private $ACTION2 = '2';// 好友添加请求
	private $ACTION3 = '3';// 同意好友添加请求
	private $ACTION4 = '4';// 拒绝了好友添加请求
	
	protected $model_model;
	protected $constant_model;
	public function _initialize() {
		 parent::_initialize();
		 $this->model_model = D("Common/AppUser");
		 $this->constant_model = D("Common/Constant");
	}
	
	
	/**登录*/
	public function login_post(){
		$user_account=I("user_account",'');//用户账号
		$type=I("type",'');//登录类型
		$password=I("password",'');//登录密码
		$result=$this->_login_post($user_account,$type,$password);
		if($result===true){//登录成功
			$this->ajaxSuccessReturn(sp_get_current_user());
		}else{//登录失败
			$this->ajaxErrorReturn($result);
		}
	}
	
	/**获取用户详情*/
	public function get_user_detail(){
		$user_uniq_id=I('user_uniq_id','');
		$cur_user=sp_get_current_user();
		if($cur_user===false){
			$this->ajaxErrorReturn("您还未登录 请登陆后操作");
		}else{
			$user=$this->model_model->where("user_uniq_id='%s'",array($user_uniq_id))->find();
			if(empty($user)){
				$this->ajaxErrorReturn("账号不存在！");
			}
			///获取备注
			$user_friend=M('UserFriend')->where("(user_uniq_id='$cur_user[user_uniq_id]' and friend_uniq_id='$user_uniq_id') or (user_uniq_id='$user_uniq_id' and friend_uniq_id='$cur_user[user_uniq_id]')")->find();
			if($user_friend==FALSE){//不是好友
				$user['is_friend']="0";
				$user['friend_mark']="";
			}else{
				$user['is_friend']="1";
				if($user_uniq_id==$user_friend['friend_uniq_id']){
					$user['friend_mark']=$user_friend["friend_mark"];
				}elseif($user_uniq_id==$user_friend['user_uniq_id']){
					$user['friend_mark']=$user_friend["user_mark"];;
				}
			}
			$hx_result=$this->userDetails($user_uniq_id);
			if(empty($hx_result['error'])){// 访问接口成功
				$user['activated']=$hx_result['entities'][0]['activated'];
				$this->ajaxSuccessReturn($user);
			}else{
			    \Think\Log::write('获取用户详情  user_uniq_id='.$user['user_uniq_id']." 出错");
				\Think\Log::write(json_encode($hx_result));
				$this->ajaxErrorReturn("环信错误代码--error:".$hx_result['error'].'--error_description:'.$hx_result['error_description']);
			}
		}
	}
	
		/**修改备注*/
	public function update_friend_mark(){
		$user=sp_get_current_user();
		$friend_uniq_id=I('friend_uniq_id','');
		$friend_mark=I('friend_mark','');
		if($user===false){
			$this->ajaxErrorReturn("您还未登录或者长时间为登录 请登陆后操作");
		}else{
			$user_friend=M('UserFriend')->where("(user_uniq_id='$user[user_uniq_id]' and friend_uniq_id='$friend_uniq_id') or (user_uniq_id='$friend_uniq_id' and friend_uniq_id='$user[user_uniq_id]')")->find();
			if(empty($user_friend)){
				$this->ajaxErrorReturn("好友关系不存在！");
			}else{
				    //我来为好友添加备注
				if($friend_uniq_id==$user_friend['friend_uniq_id']){
					$user_friend['friend_mark']=$friend_mark;
				}elseif($friend_uniq_id==$user_friend['user_uniq_id']){
					//好友为我添加备注
					$user_friend['user_mark']=$friend_mark;
				}
					M('UserFriend')->save($user_friend);
					$this->ajaxSuccessReturn("成功");
			}
		}
	}
	/*手机号码注册*/
	public function mobile_register(){
		$user_account=I('user_account','');
		$message_code=I('message_code','xxxxxx');
		$password=I('password','');
		if(session('message_code')!=$message_code){// 验证码验证
			$this->ajaxErrorReturn('验证码错误！');
		}
		if(preg_match("/^1[34578]{1}\d{9}$/",$user_account)){
			$result=$this->_register($user_account,1,$password);
			if($result===true){//注册成功
				$this->ajaxSuccessReturn(sp_get_current_user());
			}else{//登录失败
				$this->ajaxErrorReturn($result);
			}
		}else{
			$this->ajaxErrorReturn('手机号码格式错误!');
		}
	}
	/**
	 * 获取短信验证码*/
	public function get_msg_code(){
		$user_account=I('user_account','');
		$type=I("type",1);
		if(preg_match("/^1[34578]{1}\d{9}$/",$user_account)){
				if($type==1){
					$count=$this->model_model->where("user_account='%s'",array($user_account))->count(1);
					session("user_account",$user_account);
					if($count<1){
						$template=xw_send_code($user_account);
						if($template['status']==1){// 短信发送成功
							$this->ajaxSuccessReturn('');
						}else{// 短信发送失败
							$this->ajaxErrorReturn($template['msg']);
						}
					}else{
						$this->ajaxErrorReturn('手机号码已经注册!');
					}
				}elseif($type==2){
					$count=$this->model_model->where("user_account='%s'",array($user_account))->count(1);
					session("user_account",$user_account);
					if($count>0){
						$template=xw_send_code($user_account);
						if($template['status']==1){// 短信发送成功
							$this->ajaxSuccessReturn('');
						}else{// 短信发送失败
							$this->ajaxErrorReturn($template['msg']);
						}
					}else{
						$this->ajaxErrorReturn('手机号码已经注册!');
					}
				
				}
		}else{
			$this->ajaxErrorReturn('手机号码格式错误!');
		}
	}
	/**添加好友请求*/
	function add_friend_request(){
		$user=sp_get_current_user();
		$friend_uniq_id=I('friend_uniq_id','');
		$keywords=I("keywords",'');
		if($friend_uniq_id==$user['user_uniq_id']){
			$this->ajaxErrorReturn("自己不能添加自己为好友");
		}		
		if(sp_get_current_user()===false){
			$this->ajaxErrorReturn("您还未登录 请登陆后操作");
		}else{
			$freind=$this->model_model->where("user_uniq_id='%s'",array($friend_uniq_id))->count(1);
			if($freind!=1){
				$this->ajaxErrorReturn('好友不存在！');
			}
			/*判断是否已经是好友了*/
			$is_friend=M('UserFriend')->where("(user_uniq_id='$user[user_uniq_id]' and friend_uniq_id='$friend_uniq_id') or (user_uniq_id='$friend_uniq_id' and friend_uniq_id='$user[user_uniq_id]')")->count(1);
			if($is_friend>0){
				$this->ajaxErrorReturn("不允许重复添加好友！");
			}
			//发送透传消息
			    $action=$this->getUserName($user).'请求添加您为好友';
				$ext['sender']=$user['user_uniq_id'];
				$ext['acceptor']=$friend_uniq_id;
				$ext['content']=$action;
				$ext['keywords']=$keywords;
				$hx_result=$this->yy_hxSendCmd($user['user_uniq_id'], array($friend_uniq_id), $this->ACTION2, $target_type = "users", $ext);
			\Think\Log::write('添加好友请求 发送透传消息 add_friend_request--'.json_encode($hx_result));
			if(empty($hx_result['error'])){
				$this->ajaxSuccessReturn("","已发送申请!");
			}else{
				$this->ajaxErrorReturn("add_friend_request 环信消息返回！".json_encode($hx_result));
			}
		}
	}
	
	/**同意添加好友申请*/
	public function agree_add_friend(){
		$user=sp_get_current_user();
		$friend_uniq_id=I('friend_uniq_id','');
		if($friend_uniq_id==$user['user_uniq_id']){
			$this->ajaxErrorReturn("自己不能添加自己为好友");
		}	
		if(sp_get_current_user()===false){
			$this->ajaxErrorReturn("您还未登录 请登陆后操作");
		}else{
			$freind=$this->model_model->where("user_uniq_id='%s'",array($friend_uniq_id))->count(1);
			if($freind!=1){
				$this->ajaxErrorReturn('好友不存在！');
			}else{
				/*判断是否已经是好友了*/
				$is_friend=M('UserFriend')->where("(user_uniq_id='$user[user_uniq_id]' and friend_uniq_id='$friend_uniq_id') or (user_uniq_id='$friend_uniq_id' and friend_uniq_id='$user[user_uniq_id]')")->count(1);
				if($is_friend>0){
					$this->ajaxErrorReturn("不允许重复添加好友！");
				}
				$hx_result=$this->addFriend($user['user_uniq_id'], $friend_uniq_id);
			    if(empty($hx_result['error'])){// 访问接口成功
					if(M('UserFriend')->add(array('user_uniq_id'=>$user['user_uniq_id'],'friend_uniq_id'=>$friend_uniq_id))){
						$this->ajaxSuccessReturn('');
					}else{
						$this->ajaxErrorReturn("好友添加失败！");
					}
					
				}else{
				    \Think\Log::write('添加好友  user_uniq_id='.$user['user_uniq_id']." 出错");
					\Think\Log::write(json_encode($hx_result));
					$this->ajaxErrorReturn("环信错误代码--error:".$hx_result['error'].'--error_description:'.$hx_result['error_description']);
				}
			}
		}
	}

	/**拒绝添加好友申请*/
	public function refuse_add_friend(){
		$user=sp_get_current_user();
		$friend_uniq_id=I('friend_uniq_id','');
		$keywords=I("keywords",'');
		if($user===false){
			$this->ajaxErrorReturn("您还未登录 请登陆后操作");
		}else{
			$freind=$this->model_model->where("user_uniq_id='%s'",array($friend_uniq_id))->count(1);
			if($freind!=1){
				$this->ajaxErrorReturn('用户不存在！');
			}else{
				//发送透传消息
			    $action=$this->getUserName($user).'拒绝添加您为好友';
				$ext['sender']=$user['user_uniq_id'];
				$ext['acceptor']=$friend_uniq_id;
				$ext['content']=$action;
				$ext['keywords']=$keywords;
				$hx_result=$this->yy_hxSendCmd($user['user_uniq_id'], array($friend_uniq_id), $this->ACTION4, $target_type = "users", $ext);
			    \Think\Log::write('拒绝添加好友请求 发送透传消息 refuse_add_friend--'.json_encode($hx_result));
			
			    if(empty($hx_result['error'])){// 访问接口成功
					$this->ajaxSuccessReturn('');
				}else{
				    \Think\Log::write('添加好友  user_uniq_id='.$user['user_uniq_id']." 出错");
					\Think\Log::write(json_encode($hx_result));
					$this->ajaxErrorReturn("环信错误代码--error:".$hx_result['error'].'--error_description:'.$hx_result['error_description']);
				}
			}
		}
	}
	
	/*获取用户列表*/
	public function get_user_list(){
			$user=$this->_login_varify();	 	
			$keywords=I("keywords",'');
			$p=I("p");
			if(empty($keywords)){// 搜索全部用户
				$where="1=1  and user_uniq_id !='$user[user_uniq_id]' and is_visible=1";
			}else{//搜索指定用户
				$where="(user_uniq_id='$keywords' or nick like '%$keywords%' or user_account='$keywords') and user_uniq_id !='$user[user_uniq_id]' and is_visible=1";
			}
				$count=$this->model_model->where($where)->count(1);
				$page=$this->page($count,1000);
				if($p>($page->Total_Pages)){
					$this->ajaxErrorReturn('没有更多的记录');
				}
				$field="id,nick,sex,picon,signature,grade,user_uniq_id,balance,icon";
				$result['list']=$this->model_model->field($field)->where($where)->limit($page->firstRow . ',' . $page->listRows)->select();
				$result['p']=$p;
				$result['total_pages']=$page->Total_Pages;
				
			    $friend_uniq_ids=M("UserFriend")->where("user_uniq_id='$user[user_uniq_id]' or  friend_uniq_id='$user[user_uniq_id]'")->getField("id,user_uniq_id,friend_uniq_id");
				foreach ($friend_uniq_ids as $key => $value) {
					$temp[]=$value['user_uniq_id'];
					$temp[]=$value['friend_uniq_id'];
				}
				foreach ($result['list'] as $key => $value) {
					if(in_array($value['user_uniq_id'], $temp)){
						$result['list'][$key]['is_friend']=1;
					}else {
						$result['list'][$key]['is_friend']=2;
					}
				}
				$this->ajaxSuccessReturn($result);
		
	}
	
	/*获取好友列表*/
	public function get_friend_list(){
		$user=sp_get_current_user();
		if($user==false){
			$this->ajaxErrorReturn("您还未登录");
		}else{
				$keywords=I("keywords",'');
				$friend_uniq_ids[]="0";
				
			    $temp=M("UserFriend")->where("user_uniq_id='$user[user_uniq_id]' or  friend_uniq_id='$user[user_uniq_id]'")->getField("id,user_uniq_id,friend_uniq_id");
				foreach ($temp as $key => $value) {
					$friend_uniq_ids[]=$value['user_uniq_id'];
					$friend_uniq_ids[]=$value['friend_uniq_id'];
				}
				//去掉重复 屏蔽自己
				$merges_str=implode(',',array_merge(array_diff(array_unique($friend_uniq_ids),array("$user[user_uniq_id]"))));
			if(empty($keywords)){// 搜索全部好友
				$where="1=1 and  a.user_uniq_id in($merges_str)";
			}else{//搜索指定好友
				$where="1=1  and a.user_uniq_id in($merges_str) and ((a.user_uniq_id='$keywords' or a.nick like '%$keywords%' or a.user_account='$keywords') or ((b.user_uniq_id='$user[user_uniq_id]' and b.friend_mark like '%$keywords%') or (b.user_uniq_id='$user[friend_uniq_id]' and b.user_mark like '%$keywords%'))) ";
			}
				$field="a.nick,a.sex,a.picon,a.signature,a.grade,a.user_uniq_id,a.balance,a.icon,if(b.user_uniq_id='$user[user_uniq_id]',b.friend_mark,b.user_mark) as friend_mark";
				$list=$this->model_model->field($field)->alias("a")->join(array("left join m_user_friend as b on ((a.user_uniq_id=b.user_uniq_id and b.friend_uniq_id='$user[user_uniq_id]' ) or (a.user_uniq_id=b.friend_uniq_id and b.user_uniq_id='$user[user_uniq_id]'))"))->where($where)->select();
				$this->ajaxSuccessReturn($list);
		}
	}
	
	/*删除好友*/
	public function delete_friend(){
		$user=sp_get_current_user();
		if($user==false){
			$this->ajaxErrorReturn("您还未登录");
		}else{
			$friend_uniq_id=I('friend_uniq_id','');
			M('UserFriend')->where("(user_uniq_id='%s' and friend_uniq_id='%s') or (user_uniq_id='%s' and friend_uniq_id='%s')",array($user['user_uniq_id'],$friend_uniq_id,$friend_uniq_id,$user['user_uniq_id']))->delete();
			$hx_result=$this->deleteFriend($user['user_uniq_id'],$friend_uniq_id);
			\Think\Log::write($user['user_uniq_id'].'删除好友--'.$friend_uniq_id.'环信返回值---'.json_encode($hx_result));
			if(empty($hx_result['error'])){// 好友删除成功 发送透传消息
				$action=$this->getUserName($user).'和你解除了好友关系';
				$ext['sender']=$user['user_uniq_id'];
				$ext['acceptor']=$friend_uniq_id;
				$ext['content']=$action;
				$this->yy_hxSendCmd($user['user_uniq_id'], array($friend_uniq_id), $this->ACTION1, $target_type = "users", $ext);
			}
			$this->ajaxSuccessReturn("");
		}	
	}
	
	public function test(){
		
			    $action=$this->getUserName($user).'请求添加您为好友';
				$ext['sender']=$user['user_uniq_id'];
				$ext['acceptor']=$friend_uniq_id;
				$ext['content']=$action;
				$ext['keywords']=$keywords;
				//$hx_result=$this->yy_hxSendCmd($user['user_uniq_id'], array($friend_uniq_id), $this->ACTION2, $target_type = "users", $ext);
					
				$result=$this->yy_hxSendCmd("131211314", array("501211249","131211314"), $this->ACTION2, $target_type = "users", $ext);
				var_dump($result);
	}
	
	/*添加所有用户为好友*/
	public function add_all_user(){
	    	$user=$this->_login_varify();
		 	$temp=M("UserFriend")->where("user_uniq_id='$user[user_uniq_id]' or  friend_uniq_id='$user[user_uniq_id]'")->getField("id,user_uniq_id,friend_uniq_id");
				foreach ($temp as $key => $value) {
					$friend_uniq_ids[]=$value['user_uniq_id'];
					$friend_uniq_ids[]=$value['friend_uniq_id'];
				}
			$all_user_id=$this->model_model->where("user_uniq_id!='$user[user_uniq_id]'")->getField("user_uniq_id",TRUE);	
				//去掉重复 屏蔽自己
			$friend_ids=array_diff(array_unique($friend_uniq_ids),array("$user[user_uniq_id]"));
			/**可以被添加的好友*/
			$able_add=array_merge(array_diff($all_user_id,$friend_ids));
			foreach ($able_add as $key => $value) {
				$hx_result=$this->addFriend($user['user_uniq_id'], $value);
			    if(empty($hx_result['error'])){// 访问接口成功
					M('UserFriend')->add(array('user_uniq_id'=>$user['user_uniq_id'],'friend_uniq_id'=>$value));
				}
			}
			$this->ajaxSuccessReturn("","成功");
	}
	
	public function get_all_data(){
		var_dump('message_code--'.session('message_code'));
		var_dump('---------------AppUser-----------------');
		var_dump(session('user'));
		var_dump('---------------------------------');
	}
	
	/*获取根系提示*/
	public function get_update_tips(){
		$contant=M("Constant")->field("id,create_time,mark")->where("id=834 or pname='版本内容提示'")->find();
		$this->ajaxSuccessReturn($contant,"成功");
	}
	///////////////////////////////////////////////////////////////////////
	/**
	 * 授权注册模式 || 批量注册
	 * $user_account 用户账号 
	 * $type 账号   1 手机号码 2 qq 登录 3 微信登录 4新浪微博
	 * $password 登录密码
	 */
    private function _register($user_account='',$type,$password){
    	if(empty(trim($user_account))){
    		return "user_account 不能为空！";
    	}
		if(in_array($type,array('1','2','3','4'))==false){
			return "type 范围必须是 1,2,3,4";
		}
		$user_uniq_id=$this->model_model->create_user_uniq_id();// 用户互动号
		$user['user_uniq_id']=$user_uniq_id;
		$user['user_account']=trim($user_account);
		//$user['icon']=$this->model_model->setIcon();
		$user['type']=$type;
		$user['password']=$type==1?$password:'';// 如果手机注册 则需要密码
		$user['nick']=$user_uniq_id;// 用户注册时候的昵称
		/** 本地注册*/
		$data=$this->model_model->create($user);
		if($data){
		  if($this->model_model->add($data)){
		  	/** 注册环信*/
		  	$options['username']=$user_uniq_id;//环信id
			$options['password']="123456";//环信登录密码
			$options['nickname']=$user_uniq_id;//环信登录密码
    		$hx_result=$this->accreditRegister($options);
			if(empty($hx_result['error'])){// 注册成功
				$new_user=$this->model_model->where("user_account='%s'",array($user_account))->find();
				/*添加自己为好友*/
				//$this->addFriend($user_uniq_id, $user_uniq_id);
				//M("UserFriend")->add(array('user_uniq_id'=>$user_uniq_id,'friend_uniq_id'=>$user_uniq_id));
				session(array('name'=>'user','expire'=>2*24*3600));
				session('user',$new_user);
				return true;
			}else{
			    \Think\Log::write('注册user_uniq_id='.$user_uniq_id." 出错");
				\Think\Log::write(json_encode($hx_result));
				return "_register 环信错误代码--error:".$hx_result['error'].'--error_description:'.$hx_result['error_description'];
			}
		  }
		}else{
			$error=$this->model_model->getError();
			return $error;
		}
    }
	/**登录*/
	function _login_post($user_account='',$type,$password=''){
		if(empty(trim($user_account))){
    		return "user_account 不能为空！";
    	}
		if(in_array($type,array('1','2','3','4'))==false){
			return "type 范围必须是 1,2,3,4";
		}
		if($type==1){//手机号码登陆
			$user=$this->model_model->where("user_account='%s' and password='%s'",array($user_account,$password))->find();
			if(empty($user)){
				return "账号或密码错误！";
			}else{
				session(array('name'=>'user','expire'=>2*24*3600));
				session('user',$user);
				return true;
			}
		}elseif($type==2 ||$type==3 ||$type==4){//qq 登录 或者微信 登录  或者 //新浪登录
			$user=$this->model_model->where("user_account='%s' ",array($user_account))->find();
			if(empty($user)){
				return $this->_register($user_account,$type, $password);
			}else{
				session(array('name'=>'user','expire'=>2*24*3600));
				session('user',$user);
				return true;
			}
		}
	}
	
	/*获取用户名称*/
	function getUserName($user){
		if(empty($user['nick'])){
			return $user['user_uniq_id'];
		}else{
			return $user['nick'];
		}
	}
		private function _login_varify(){
		$user=sp_get_current_user();
			if($user==false){
				$this->ajaxErrorReturn("请登陆后操作！");
				exit();
			}else{
				return $user;
			}
	}
		/*登出*/
		public function loginOut(){
			session('message_code',null);
			session("user_account",null);
			session('user',null);
			$this->ajaxSuccessReturn("");
		}
}

